package logic.common.team;

import java.util.HashMap;

import factories.WeaponFactory;
import logic.common.team.processes.MSWeaponProcess;
import logic.ships.mothership.MotherShip;
import logic.weapons.Weapon;
import logic.weapons.WeaponProperties;
import logic.weapons.WeaponType;

public class MSWeaponAction extends TeamAction {
		
	private static final WeaponType[] types = new WeaponType[] { WeaponType.Artillary, WeaponType.Energy };
	
	private MotherShip ms;
	private HashMap<WeaponType, Integer> openSlots;
	
	public MSWeaponAction(Team team) {
		super(team);
		
		ms = team.getMotherShip();
		
		openSlots = new HashMap<WeaponType, Integer>();
		for(WeaponType type : types) {
			openSlots.put(type, Integer.valueOf(ms.getWeapontSlotsNumber(type)));
		}
	}
	
	@Override
	public void performAction() {
		for(WeaponType type : types) {
			if(necessary(type)) {
				int open = openSlots.get(type).intValue();
				if(open > 0) addWeapons(type);
			}
		}
	}
	
	private boolean necessary(WeaponType type) {
		switch(type) {
			case Artillary: return artillaryNecessary();
			case Energy: return energyNecessary();
		}
		return false;
	}
	
	private boolean artillaryNecessary() {
		return true;
	}
	
	private boolean energyNecessary() {
		if(!team.getEnemyTeam().getFrigates().isEmpty()) return true;
		
		if(team.getTeamMoney() >= 1200) return true;
		
		return team.getPendingTeamProcesses().isEmpty();
	}
	
	private void addWeapons(WeaponType type) {
		WeaponProperties props = team.getMSWeaponProperties(type);
		int costs = props.getCosts();
		if(costs > team.getTeamMoney()) return;
		
		String weaponName = team.getMSWeaponName(type);
		
		int open = openSlots.get(type).intValue();
		for(int i = 0; i < open; i++) {
			if(costs <= team.getTeamMoney()) {
				Weapon weapon = WeaponFactory.createNewWeapon(weaponName, ms, props);
				team.addTeamProcess(new MSWeaponProcess(team, weapon));
				team.spendTeamMoney(costs);
				open--;
				openSlots.put(type, Integer.valueOf(open));
			} else break;
		}
	}
}